from django.db import models
from django.utils.functional import lazy


class DynamicChoicesField(models.CharField):
    def __init__(self, *args, **kwargs):
        print(type(self))
        # 从参数中获取生成 choices 的方法
        self.choices_getter = kwargs.pop("choices_getter", None)
        super().__init__(*args, **kwargs)

    def contribute_to_class(self, cls, name, private_only=False):
        # 若存在 choices_getter，则通过该方法获取 choices 并赋值给 choices 字段
        # 仅当关联到子类时执行
        if not cls._meta.abstract and self.choices_getter:
            if isinstance(self.choices_getter, str):
                method = getattr(cls, self.choices_getter)
                self.choices = method()
            else:
                self.choices = self.choices_getter(cls)
        super().contribute_to_class(cls, name, private_only)


# class DynamicChoicesField(models.CharField):
#     """
#         自定义字段，动态设置 choices
#         """
#     def __init__(self, *args, **kwargs):
#         self.choices_getter = kwargs.pop('choices_getter', None)
#         super().__init__(*args, **kwargs)
#
#     def deconstruct(self):
#         # 必须实现序列化逻辑
#         name, path, args, kwargs = super().deconstruct()
#         if self.choices_getter:
#             kwargs['choices_getter'] = self.choices_getter
#         return name, path, args, kwargs
#
#     def contribute_to_class(self, cls, name, private_only=False):
#         # 关键修改：添加 private_only 参数
#         if self.choices_getter:
#             self.choices = self.choices_getter(cls)
#         super().contribute_to_class(cls, name, private_only=private_only)


#
# class DynamicChoicesField(models.CharField):
#     def __init__(self, *args, **kwargs):
#         choices_getter = kwargs.pop('choices_getter', None)
#
#         # 延迟执行 choices 获取
#         if choices_getter:
#             kwargs['choices'] = lazy(choices_getter, list)()
#
#         super().__init__(*args, **kwargs)
